package org.example.dingtalkintegrationservice.pojo.converter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.persistence.AttributeConverter;
import jakarta.persistence.Converter;


import java.util.HashMap;
import java.util.Map;

/**
 * @author pc
 */
@Converter
public class MapConverter implements AttributeConverter<Map<String, Object>, String> {

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    @Override
    public String convertToDatabaseColumn(Map<String, Object> attribute) {
        try {
            return attribute != null ? OBJECT_MAPPER.writeValueAsString(attribute) : null;
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Could not convert Map<String, Object> to JSON string.", e);
        }
    }

    @Override
    public Map<String, Object> convertToEntityAttribute(String dbData) {
        try {
            return dbData != null ? OBJECT_MAPPER.readValue(dbData, new TypeReference<>() {}) : new HashMap<String, Object>();
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Could not convert JSON string to Map<String, Object>.", e);
        }
    }
}